import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_novel/config/response_model.dart';
import 'package:flutter_novel/detail/bloc/home_commits_list_event.dart';
import 'package:flutter_novel/detail/bloc/home_commits_list_state.dart';
import 'package:flutter_novel/detail/data/model/commit_model_entity.dart';
import 'package:flutter_novel/detail/data/repository/home_repository.dart';
import 'package:flutter_novel/widget/loading_util.dart';

class HomeCommitsListBloc extends Bloc<HomeCommitsListEvent, HomeCommitsListState> {
  HomeCommitsListBloc() : super(HomeCommitsListState()) {
    on<GetHomeCommitsListEvent>(_onGetHomeCommitsList);
  }

  void _onGetHomeCommitsList(
    GetHomeCommitsListEvent event,
    Emitter<HomeCommitsListState> emit,
  ) async {
    LoadingUtil.show();
    ResponseModel model = await HomeRepository.getCommitsData<CommitModelEntity>();
    CommitModelEntity? commitModelEntity = model.data;
    LoadingUtil.dismiss();
    if ((commitModelEntity?.reviews ?? []).isNotEmpty) {
      state.list.addAll(commitModelEntity!.reviews!);
      var nState = state.clone()..loadFinish = true;
      emit(nState);
    } else {
      emit(state.clone()..loadFinish = true);
    }
  }
}
